package com.nfu.zlsp.dev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nfu.zlsp.dev.common.constants.TheConstant;
import com.nfu.zlsp.dev.common.utils.PageUtils;
import com.nfu.zlsp.dev.common.utils.Query;
import com.nfu.zlsp.dev.common.utils.R;
import com.nfu.zlsp.dev.dao.UserDao;
import com.nfu.zlsp.dev.entity.UserEntity;
import com.nfu.zlsp.dev.service.UserService;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public String saveUser(UserEntity user) {

        //查询是账号是否被注册
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>()
                .eq("number", user.getNumber()).eq("user_type", user.getUserType()));
        if(userEntity != null){
            return TheConstant.RETURN_FAIL;
        }else{
            //没被注册 进行数据保存
            this.save(user);
            return TheConstant.RETURN_SUCCESS;
        }
    }

    /**
     * 判断用户登录信息
     * @param user
     * @return
     */
    @Override
    public UserEntity  queryUserForLogin(UserEntity user) {
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("number", user.getNumber())
                .eq("password", user.getPassword()).eq("user_type", user.getUserType()));
        return userEntity;
    }

    @Transactional
    @Override
    public R updatePwdById(Map<String, Object> params) {
        String id = (String) params.get("id");
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("id", id));
        if (userEntity != null) {
            if (!userEntity.getPassword().equals(params.get("oldPwd")) ){
                return R.ok().put("data","修改失败,旧密码输入错误");
            }else{
                UserEntity user = new UserEntity();
                user.setId(id);
                user.setPassword((String) params.get("newPwd"));
                int result = this.baseMapper.updateById(user);
                if (result >= 1){
                    return R.ok().put("data","密码修改成功");
                }else {
                    return R.ok().put("data","密码修改失败");
                }
            }
        }else {
            return R.ok().put("data","密码修改失败");
        }

    }


}




















